package sword.chapter5HashMap;

import java.util.HashMap;
import java.util.Map;

/**
 * 有效的变位词
 * map key存字符 value存出现数量
 * s1 ++
 * s2 -- 同时判断是否还能操作
 *
 * @author K
 * @date 2021-12-02 20:26
 */
public class S32IsAnagram {

    public static boolean s32(String str1, String str2) {
        if (str1.equals(str2)) {
            return false;
        }
        if (str1.length() != str2.length()) {
            return false;
        }

        Map<Character, Integer> counts = new HashMap<>();
        for (char ch : str1.toCharArray()) {
            counts.put(ch, counts.getOrDefault(ch, 0) + 1);
        }

        for (char ch : str2.toCharArray()) {
            if (counts.getOrDefault(ch, 0) == 0)
                return false;

            counts.put(ch, counts.get(ch) - 1);
        }

        return true;
    }

    public static boolean s32A(String str1, String str2) {
        if (str1.equals(str2)) {
            return false;
        }
        if (str1.length() != str2.length()) {
            return false;
        }

        int[] counts = new int[26];
        for (int i = 0; i < str1.length(); i++) {
            counts[str1.charAt(i) - 'a']++;
        }

        for (int i = 0; i < str2.length(); i++) {
            if (counts[str2.charAt(i) - 'a'] == 0) {
                return false;
            }
            counts[str2.charAt(i) - 'a']--;
        }

        return true;
    }

    public static void main(String[] args) {
        String s1 = "anagram";
        String s2 = "nagaram";
        boolean result = s32(s1, s2);
        boolean result2 = s32A(s1, s2);
        System.out.println();
    }
}
